package com.glsc.ngateway.opmanage.aspect;


import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.Url;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.User;
import com.glsc.ngateway.opmanage.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.MysqlUserRepository;
import com.glsc.ngateway.opmanage.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author pggsnap
 * @date 2019/12/25
 */
@Component
public class UserCache {
    private Map<String, User> cache;
    @Resource
    private MysqlUserRepository userRepo;
    @Resource
    private UserService userService;

    @Autowired
    public void setUserRepo(MysqlUserRepository userRepo) {
        this.userRepo = userRepo;
    }


    public UserCache() {
        cache = new HashMap<>();
    }

    public void put(String username, User user) {
        cache.put(username, user);
    }

    public User get(String username) {
        User user = cache.get(username);
        if (user == null) {
            user = userRepo.findByUsername(username);
            if (user == null){
                userService.saveUserByUserName(username);
                user = userRepo.findByUsername(username);
            }
            Set<Url> urls = new HashSet<>();
            if (user != null){
                user.getRoles().forEach(role -> urls.addAll(role.getUrls()));
                user.setUrls(urls);
            }
        }
        return user;
    }

    public User get(HttpServletRequest request) {
        String token = request.getHeader("token");
        String username = JwtHelper.parseToken(token);
        if (username == null) {
            throw PlatformException.error("token不存在或者已过期", true, false);
        }
        return get(username);
    }

    public String getOpNo(HttpServletRequest request) {
        return get(request).getUsername();
    }

    /*public boolean isRoleTrade(HttpServletRequest request) {
        User user = get(request);
        for (Role role : user.getRoles()) {
            if (role.getName().equals(DictValueUtil.ROLE_TRADER)) {
                return true;
            }
        }
        return false;
    }

    public boolean isRoleManager(HttpServletRequest request) {
        User user = get(request);
        for (Role role : user.getRoles()) {
            if (role.getName().equals("ROLE_MANAGER")) {
                return true;
            }
        }
        return false;
    }*/

}
